`
https://leetcode.cn/problems/maximum-tastiness-of-candy-basket/
`

/**
 * @param {number[]} price
 * @param {number} k
 * @return {number}
 */
var maximumTastiness = function (price, k) {
  // 同 LC 1552. 两球之间的磁力
  const n = price.length
  price.sort((a, b) => a - b)

  // 能否从 price 中选出 k 个糖果，使得任意两个价格差的绝对值 >= d
  const check = (d) => {
    let count = 1
    let last = price[0]
    for (let i = 1; i < n; i++) {
      if (Math.abs(price[i] - last) >= d) {
        last = price[i]
        count++
        if (count >= k) return true
      }
    }
    return false
  }

  let left = 0, right = price.at(-1) - price[0] + 1
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      // 可能还有更大的甜蜜度
      left = mid
    } else {
      // 甜蜜度太大，需要往小调整
      right = mid
    }
  }
  return left
};